package com.bangyu.monitor.modular.system.controller;

import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.bangyu.monitor.modular.system.biz.FileDownloadBiz;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Auther: zhangxue
 * @Date: 19/5/27 20:24
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/file/download/")
public class FileDownloadController extends BaseController {

    @Resource
    FileDownloadBiz fileDownloadBiz;

    @RequestMapping(value = "wordReport",method = RequestMethod.POST)
    public void wordReport(@RequestParam(value = "beamNo") String beamNo,
            @RequestParam("img64Url") String img64Url,
            @RequestParam("startDate") String startDate,
            @RequestParam("endDate") String endDate,
            HttpServletRequest request
            ,
            HttpServletResponse response){

        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            File file = fileDownloadBiz.reportDownload(beamNo,startDate,endDate,img64Url);

            String fileName = processFileName(request,"桥梁监控报告.docx");

            in = new BufferedInputStream(new FileInputStream(file));
            out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType(new MimetypesFileTypeMap().getContentType(file));
            response.setHeader("Content-disposition", "attachment;filename="+fileName);// 设置头部信息
            byte[] buffer = new byte[10240];
            int length = 0;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.flush();
        }catch (Exception e){
            log.error("download report error",e);
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {

            }
        }

    }

    private String processFileName(HttpServletRequest request,String fileNames)
            throws UnsupportedEncodingException {
        String codedfilename = null;
        String agent = request.getHeader("USER-AGENT");
        if (null != agent && -1 != agent.indexOf("MSIE") || null != agent
                && -1 != agent.indexOf("Trident")) {// ie
            String name = java.net.URLEncoder.encode(fileNames, "UTF8");
            codedfilename = name;
        } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
            codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
        }
        return codedfilename;
    }

}
